package com.quectel.core.module.car.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.car.dao.CarDao;
import com.quectel.core.module.car.dto.CarDto;
import com.quectel.core.module.car.dto.datav.CarCountDto;
import com.quectel.core.module.car.entity.CarEntity;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-09 14:20:06
 */
@DubboService
public class CarServiceImpl extends ServiceImpl<CarDao, CarEntity> implements CarService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CarServiceImpl.class);

    private static final String CAR_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "CAR_CACHE_BY_ID:";
    private static final String CAR_CACHE_BY_FLAG = RedisCacheConstants.PROJECT_NAME + "CAR_CACHE_BY_FLAG:";

    @Autowired
    private CarDao carDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private VillageRoomService villageRoomService;

    /**
     * 通过手机号查询车辆列表，不区分租户
     *
     * @param mobile
     * @return
     */
    @Override
    public List<CarDto> selectByMobile(String mobile) {
        List<CarEntity> entityList = carDao.selectList(
                new LambdaQueryWrapper<CarEntity>()
                        .eq(CarEntity::getOwnerMobile, mobile)
        );
        return CopyUtils.copyList(entityList, CarDto.class);
    }

    @Override
    public void saveBatch(List<CarDto> carDtos) {
        List<CarEntity> carEntities = CopyUtils.copyList(carDtos, CarEntity.class);
        for (CarEntity carEntity : carEntities) {
            carEntity.setId(Snowflake.nextId());
        }
        super.saveBatch(carEntities);
    }

    @Override
    public CarCountDto countCar(Map<String, Object> params) {
        return carDao.countCar(params);
    }

    @Override
    public CarDto selectOneByCache(Long villageId, String license, Byte licenseColor) {
        return CacheKit.cacheToRedis(() -> selectOne(villageId, license, licenseColor)
                , CAR_CACHE_BY_FLAG + String.format("%s_%s_%s", villageId, license, licenseColor),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS);
    }


    @Override
    public CarDto selectOne(Long villageId, String license, Byte licenseColor) {
        CarEntity entity = carDao.selectOne(
                new LambdaQueryWrapper<CarEntity>()
                        .eq(CarEntity::getVillageId, villageId)
                        .eq(CarEntity::getLicense, license)
                        .eq(CarEntity::getLicenseColor, licenseColor)
        );
        return paddingField(CopyUtils.copyObj(entity, CarDto.class));
    }

    @Override
    public CarDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                CAR_CACHE_BY_ID + id,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public CarDto selectById(Long id) {
        CarEntity entity = carDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, CarDto.class));
    }

    @Override
    public List<CarDto> queryList(Map<String, Object> params) {
        List<CarEntity> list = carDao.queryList(params);
        List<CarDto> result = CopyUtils.copyList(list, CarDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private CarDto paddingField(CarDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                if (villageDto != null) {
                    dto.setVillageName(villageDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return carDao.queryTotal(params);
    }

    @Override
    public Long save(CarDto dto) {
        CarEntity entity = CopyUtils.copyObj(dto, CarEntity.class);
        entity.setId(Snowflake.nextId());
        carDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(CarDto dto) {
        CarEntity entity = CopyUtils.copyObj(dto, CarEntity.class);
        carDao.updateById(entity);
        CacheKit.invalidRedisCache(CAR_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void updateAllColumnById(CarDto dto) {

        CarEntity entity = CopyUtils.copyObj(dto, CarEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, carDao);

        CacheKit.invalidRedisCache(CAR_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void deleteById(Long id) {
        carDao.deleteById(id);
        CacheKit.invalidRedisCache(CAR_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
